<?php
namespace app\model;

use app\common\model\_Base;

class Token extends _Base
{
    protected $updateTime = false; 

    const TOKEN_EXPIRE_TIME = 60*60*1;

    // 生成token
    public static function doCreate($user_id,$user_type = self::TYPE_USER)
    {   
       
        $token = Token::where(['user_id' => $user_id,'user_type' => $user_type])->find();
        if(!$token){
            $token = new Token;
            $token->user_id = $user_id;
            $token->user_type = $user_type;
            $token->token = random_str();
        }
        self::doExtendExpireTime($token);
        return $token->token;
    }

    // 延长token失效时间
    public static function doExtendExpireTime($token)
    {   
        $token->expire_time = time() + self::TOKEN_EXPIRE_TIME;
        $token->save();
        return true;
    }

    // 检查token
    public static function getToken($token = '')
    {   
        $token = (string)$token;
        if(!$token || strlen($token)!=32){
            return false;
        }
        $token = Token::get(['token'=>$token]);
        if(!$token || $token->expire_time<time()){
            return false;   
        }
        self::doExtendExpireTime($token);
        return $token;        
    }

    /**
     * 删除token
     * @param  integer $id 数据编号
     * @return bool       
     */
    public static function doDelete($token)
    {
        Token::where(['token'=>$token])->delete();
        return true;
    }

        /**
     * 根据ID获取用户信息
     * @param  integer $id 数据编号
     * @return bool       
     */
    public static function getUserById($id,$type = self::TYPE_USER)
    {
        switch ($type) {
            case self::TYPE_USER:
                $user = User::doDetail($id);
                break;
            case self::TYPE_ADMIN:
                $user = Admin::doDetail($id);
                break;
            default:
                break;
        }
        return $user;
    }

    /**
     * 根据登录名获取用户信息
     * @param  integer $id 数据编号
     * @return bool       
     */
    public static function getUserByName($name,$type = self::TYPE_USER)
    {
        switch ($type) {
            case self::TYPE_USER:
                $user = User::doDetail(null,$name);
                break;
            case self::TYPE_ADMIN:
                $user = Admin::doDetail(null,$name);
                break;
            default:
                break;
        }
        return $user;
    }
}